package com.crm.system.service.impl.customerManager;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.*;
import com.crm.model.entity.common.Dictionary;
import com.crm.model.entity.contactManager.Contact;
import com.crm.model.entity.contactManager.ContactExchangeCode;
import com.crm.model.entity.contactManager.ContactInformation;
import com.crm.model.entity.customerManager.*;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.customerManager.CustomerPool;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.entity.systemManager.SysParameterSetting;
import com.crm.model.qo.customerManager.CustomerPoolAddQO;
import com.crm.model.qo.customerManager.CustomerPoolQO;
import com.crm.model.vo.cluePoolManager.UserCompanyVO;
import com.crm.model.vo.contactManager.ContactInformationVO;
import com.crm.model.vo.customerManager.*;
import com.crm.service.common.DictionaryDbService;
import com.crm.service.contactManager.ContactDbService;
import com.crm.service.contactManager.ContactInformationDbService;
import com.crm.service.customerManager.CustomerContactPersonDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerPoolDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.system.service.contactManager.ContactInformationService;
import com.crm.system.service.contactManager.ContactService;
import com.crm.system.service.customerManager.CustomerPoolCompanyService;
import com.crm.system.service.customerManager.CustomerPoolRuleService;
import com.crm.system.service.customerManager.CustomerPoolService;
import com.crm.system.service.customerManager.CustomerService;
import com.crm.system.service.permissionManagement.SysCompanyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ Author ：pym
 * @ Date   ：2021/1/15 10:10
 */
@Service
@Slf4j
public class CustomerPoolServiceImpl implements CustomerPoolService {

    @Value("${esurl}")
    public String ESurl;

    @Autowired
    CustomerPoolDbService customerPoolDbService;

    @Autowired
    CustomerDbService customerDbService;

    @Autowired
    SysCompanyService sysCompanyService;

    @Autowired
    CustomerPoolCompanyService customerPoolCompanyService;

    @Autowired
    CustomerPoolRuleService customerPoolRuleService;

    @Autowired
    CustomerService customerService;

    @Autowired
    private DictionaryDbService dictionaryDbService;

    @Autowired
    private ContactDbService contactDbService;

    @Autowired
    private ContactInformationService contactInformationService;

    @Autowired
    private ContactInformationDbService contactInformationDbService;

    @Autowired
    private CustomerContactPersonDbService customerContactPersonDbService;

    @Autowired
    private FinishOrderDBservice finishOrderDBservice;

    @Autowired
    private ContactService contactService;

    @Override
    public DhPageInfo<CustomerPoolVO> selectCustomerPoolVOList(Integer pageIndex, Integer pageSize, CustomerPoolQO customerPoolQO, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        customerPoolQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(customerPoolQO.getDateType())) {
            if ("thisWeek".equals(customerPoolQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(customerPoolQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(customerPoolQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
        }

        StringBuilder order = new StringBuilder();
        order.append("defaultMarkOrder DESC");
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "customerPoolName": {
                    order.append(",customer_pool_name ").append(sortOrder);//客户池名称
                }
                break;
                case "nature": {
                    order.append(",nature ").append(sortOrder);//性质：1-全国公有池；2-分公司公有池；
                }
                break;
                case "createPeopleName": {
                    order.append(",user_name ").append(sortOrder);
                }
                break;
                case "createTm": {
                    order.append(",create_tm ").append(sortOrder);
                }
                break;
                case "tag": {
                    order.append(",tag ").append(sortOrder);
                }
                break;
                case "poolType": {
                    order.append(",pool_type ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<CustomerPoolVO> customerPoolList = null;
        if (CommonUtils.isAdmin(userAccount.getUserId())) {//超级管理员
            customerPoolList = customerPoolDbService.selectAllCustomerPoolList(customerPoolQO, dateUnit, order.toString());
        } else {//普通管理员
            String companyId = userAccount.getCompanyId();//获取登录人所在的公司
            customerPoolList = customerPoolDbService.selectNormalCustomerPoolList(customerPoolQO, dateUnit, order.toString(), companyId);
        }
        PageInfo<CustomerPoolVO> pageInfo = new PageInfo<CustomerPoolVO>(customerPoolList);
        return new DhPageInfo<CustomerPoolVO>(pageInfo, customerPoolList);
    }

    /**
     * 根据客户id查询客户详细信息
     * @param customer_id 客户id
     * @return
     */
    @Override
    public Customer customerHighSeasDetail(String customer_id) {
        return customerPoolDbService.customerHighSeasDetail(customer_id);
    }

    /**
     * 根据客户id查询公司信息
     * @param customer_id 客户id
     * @return
     */
    @Override
    public CustomerCompanyInfo getCompanyInfo(String customer_id) {
        return customerPoolDbService.getCompanyInfo(customer_id);
    }

    /**
     * 根据客户id查询公司联系人信息
     * @param pageIndex 页码
     * @param pageSize 分页大小
     * @param sortName 排序列名字
     * @param sortOrder 排序规则(asc/desc)
     * @param customer_id 客户id
     * @param isSeniorExecutive 类型是否高管   0高管  1非高管
     * @param abolishState 废止状态  1不查询废止的 2查询废止的
     * @return
     */
    @Override
    public DhPageInfo<CustomerContactPerson> customerContactPersonList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customer_id, int isSeniorExecutive,int abolishState) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        String order = "create_tm desc";

        List<CustomerContactPerson> list = customerPoolDbService.customerContactPersonList(order, customer_id, isSeniorExecutive,abolishState);
        PageInfo<CustomerContactPerson> pageInfo = new PageInfo<CustomerContactPerson>(list);
        return new DhPageInfo<CustomerContactPerson>(pageInfo, list);


    }

    @Override
    public List<CustomerContactPerson> selectContactPersonListByCustomerId(String customerId) {
        List<CustomerContactPerson> customerContactPersonList = customerPoolDbService.selectContactPersonListByCustomerId(customerId);
        return customerContactPersonList;
    }


    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean addCustomerPool(CustomerPoolAddQO customerPoolAddQO) {
        //1、根据客户池名称判断客户池是否存在，不存在则添加客户池
        CustomerPool customerPool = customerPoolDbService.selectCustomerPoolByName(customerPoolAddQO.getCustomerPoolName());
        if (customerPool == null) {
            String customerPoolId = addCustomerPoolModel(customerPoolAddQO);
            if (customerPoolAddQO.getNature() == CluePoolNatureEnum.BRANCH_PUBLIC_POOL.getCluePoolNatureCode()) {
                //2、添加公司表
                customerPoolCompanyService.addCustomerPoolCompany(customerPoolAddQO.getCompanyIdList(), customerPoolId);
            }
            //3、添加规则表
            customerPoolRuleService.addCustomerPoolRule(customerPoolAddQO, customerPoolId);
            return true;
        } else {
            return false;
        }
    }

    String addCustomerPoolModel(CustomerPoolAddQO customerPoolAddQO) {
        //获取当前用户
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String customerPoolId = CommonUtils.getGUID();
        CustomerPool customerPool = new CustomerPool();
        customerPool.setCustomerPoolId(customerPoolId);
        customerPool.setCustomerPoolName(customerPoolAddQO.getCustomerPoolName());
        //判断当前用户是否是超级管理员
        //如果不是超级管理员就
        Boolean ifAdmin = CommonUtils.isAdmin(userAccount.getUserId());
        if (!ifAdmin) {
            customerPool.setCompanyId(userAccount.getCompanyId());
            //公司名称
            SysCompany sysCompany = sysCompanyService.selectSysCompanyById(userAccount.getCompanyId());
            customerPool.setCompanyName(sysCompany.getCompanyName());
        }
        customerPool.setProvinceId(customerPoolAddQO.getProvinceId());
        customerPool.setProvinceName(customerPoolAddQO.getProvinceName());
        customerPool.setCityId(customerPoolAddQO.getCityId());
        customerPool.setCityName(customerPoolAddQO.getCityName());
        customerPool.setIndustry(customerPoolAddQO.getIndustry());
        customerPool.setSource(customerPoolAddQO.getSource());
        customerPool.setPoolType(customerPoolAddQO.getPoolType());
        customerPool.setCapacity(customerPoolAddQO.getCapacity());
        customerPool.setNature(customerPoolAddQO.getNature());
        customerPool.setPoolState(CluePoolStatusEnum.TURN_ON.getCluePoolStatus());
        customerPool.setTag(customerPoolAddQO.getTag());
        customerPool.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        Integer defaultMark = 0;//不是默认池子
        customerPool.setDefaultMark(defaultMark);
        customerPool.setCreatePeopleId(userAccount.getAccountId());
        customerPool.setCreateTm(new Date());
        customerPool.setUpdatePeopleId(userAccount.getAccountId());
        customerPool.setUpdateTm(new Date());
        customerPool.setAffiliatedCompanyId(customerPoolAddQO.getAffiliatedCompanyId());
        Boolean result = customerPoolDbService.insertCustomerPool(customerPool);
        return customerPoolId;
    }

    @Override
    public Boolean updatePoolStateById(String customerPoolId, String poolState) {
        CustomerPool customerPool = new CustomerPool();
        if (!StringUtils.isBlank(customerPoolId) && !StringUtils.isBlank(poolState)) {
            customerPool.setCustomerPoolId(customerPoolId);
            customerPool.setPoolState(Integer.parseInt(poolState));
        }
        return customerPoolDbService.updatePoolStateById(customerPool);
    }

    /**
     * 客户详情-新增联系人 同时新增客户下联系人表和联系人大表
     * @param customerContactVO  联系人实体
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean addCustomerContactPerson(CustomerContactVO customerContactVO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = true;
        String contactInformationId = CommonUtils.getGUID();

        String info = customerContactVO.getContactInformation().replaceAll("-", "");

        if(!StringUtils.isBlank(customerContactVO.getExtNumber())) {
            customerContactVO.setContactInformation(customerContactVO.getContactInformation().replaceAll("-","") + " - " + customerContactVO.getExtNumber());
        }else{
            customerContactVO.setContactInformation(customerContactVO.getContactInformation().replaceAll("-",""));
        }

        //customerContactVO.setContactInformation(customerContactVO.getContactInformation());
        if(!StringUtils.isBlank(customerContactVO.getContactId())){  //有值
            //新增联系方式
            addContactIn(customerContactVO,contactInformationId,userAccount);
        }else{

            String contactId = CommonUtils.getGUID();
            Contact contact = new Contact();
            contact.setContactId(contactId);
            contact.setContactName(customerContactVO.getContactName());
            contact.setContactPosition(customerContactVO.getContactPosition());
            contact.setContactInformation(customerContactVO.getContactInformation());
            contact.setOnTheJobSituation(customerContactVO.getOnTheJobSituation());
            contact.setProvinceId(customerContactVO.getProvinceId());
            contact.setProvinceName(customerContactVO.getProvinceName());
            contact.setCityId(customerContactVO.getCityId());
            contact.setCityName(customerContactVO.getCityName());
            contact.setIndustry(customerContactVO.getIndustry());
            contact.setCompanyAddress(customerContactVO.getCompanyAddress());
            contact.setWx(customerContactVO.getWx());
            contact.setMailBox(customerContactVO.getMailBox());
            contact.setCurrentIntention(customerContactVO.getCurrentIntention());
            contact.setFollowUpTimes(0);
            contact.setCreatePeopleId(userAccount.getAccountId());
            contact.setCreateTm(new Date());
            contact.setUpdatePeopleId(userAccount.getAccountId());
            contact.setUpdateTm(new Date());
            contact.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            contact.setContactState(customerContactVO.getContactState());
            //contact.setMemberGrade(1);
            contact.setMemberGrade(customerContactVO.getMemberGrade());
            //contact.setMergeState(Integer.parseInt(customerContactVO.getMergeState()));
            contact.setContactNature(0);
            contact.setHomeAddress(customerContactVO.getHomeAddress());
            contact.setAbolishState(1);
            contact.setIsCreate(1);
            contact.setCustomerId(customerContactVO.getCustomerId());
            contact.setAccountId(userAccount.getAccountId());
            contact.setCompanyId(userAccount.getCompanyId());
            //新增联系人管理的联系人
            Boolean result = customerPoolDbService.addContact(contact);

            customerContactVO.setContactId(contactId);
            //新增联系方式
            addContactIn(customerContactVO,contactInformationId,userAccount);

            CustomerContactPerson customerContactPerson = new CustomerContactPerson();
            String customerContactPersonId = CommonUtils.getGUID();
            customerContactPerson.setCustomerContactPersonId(customerContactPersonId);
            customerContactPerson.setContactName(customerContactVO.getContactName());
            customerContactPerson.setContactPosition(customerContactVO.getContactPosition());
            customerContactPerson.setContactInformation(customerContactVO.getContactInformation());
            customerContactPerson.setOnTheJobSituation(customerContactVO.getOnTheJobSituation());
            customerContactPerson.setIsSeniorExecutive(customerContactVO.getIsSeniorExecutive());
            customerContactPerson.setMailBox(customerContactVO.getMailBox());
            customerContactPerson.setWx(customerContactVO.getWx());
            customerContactPerson.setFollowUpTimes(0);
            customerContactPerson.setCreatePeopleId(userAccount.getAccountId());
            customerContactPerson.setCreateTm(new Date());
            customerContactPerson.setUpdatePeopleId(userAccount.getAccountId());
            customerContactPerson.setUpdateTm(new Date());
            customerContactPerson.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            customerContactPerson.setAbolishState(1);
            customerContactPerson.setContactState(customerContactVO.getContactState());
            customerContactPerson.setMergeState(Integer.parseInt(customerContactVO.getMergeState()));
            customerContactPerson.setCustomerId(customerContactVO.getCustomerId());
            customerContactPerson.setCompanyId(userAccount.getCompanyId());
            //新增客户下的联系人
            rs = customerPoolDbService.addCustomerContactPerson(customerContactPerson);

            /*//联系人类型    主联系人-1   从联系人-2        目前意向   0有意向 1无意向
            if(customerContactVO.getContactState() != null && !StringUtils.isBlank(customerContactVO.getCurrentIntention())) {
                if (1 == customerContactVO.getContactState() && "0".equals(customerContactVO.getCurrentIntention())) {
                    Customer customers = customerDbService.selectCustomerById(customerContactVO.getCustomerId());
                    if (!"1".equals(customers.getPotentialCustomers())) {
                        customers.setPotentialCustomers(1);  //意向客户
                        customers.setUpdatePeopleId(userAccount.getAccountId());
                        customers.setUpdateTm(new Date());
                        customers.setAccountId(userAccount.getAccountId());
                        rs = customerPoolDbService.updateCustomer(customers);
                    }
                }
            }*/

            //contactService.contactSendCode(info,userAccount.getAccountId(),contactId,"1");

        }

        return rs;
    }

    /**
     * 新增联系方式
     * @param customerContactVO
     * @param contactInformationId
     * @param userAccount
     * @return
     */
    public Boolean addContactIn(CustomerContactVO customerContactVO,String contactInformationId,UserAccount userAccount){
        ContactInformationVO contactInformation = new ContactInformationVO();
        contactInformation.setContactInformationId(contactInformationId);
        contactInformation.setContactInformation(customerContactVO.getContactInformation());
        contactInformation.setContactType(customerContactVO.getContactType());
        //联系方式类型  0主联系方式 1从联系方式
        contactInformation.setContactInformationType(customerContactVO.getContactInformationType());
        contactInformation.setContactId(customerContactVO.getContactId());
        contactInformation.setCustomerId(customerContactVO.getCustomerId());
        contactInformation.setCreatePeopleId(userAccount.getAccountId());
        contactInformation.setCreateTm(new Date());
        contactInformation.setUpdatePeopleId(userAccount.getAccountId());
        contactInformation.setUpdateTm(new Date());
        contactInformation.setAbolishState(1);  //废止状态  1启动 2废止
        contactInformation.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        contactInformation.setCompanyId(userAccount.getCompanyId());
        Boolean rs = contactInformationService.addContactInformation(contactInformation);
        return rs;
    }

    /**
     * 根据联系人id,回显联系人信息
     * @param customerContactPersonId 联系人id
     * @return
     */
    @Override
    public CustomerContactPerson getCustomerContactPerson(String customerContactPersonId) {
        return customerPoolDbService.getCustomerContactPerson(customerContactPersonId);
    }

    /**
     * 客户详情-修改联系人 同时修改客户下联系人表和联系人大表  存入修改记录里面
     * @param customerContactVO 联系人实体
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean updateCustomerContactPerson(CustomerContactVO customerContactVO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs =false;

        //联系人性质  0企业联系人  1非企业联系人
        List<Contact> contactList = contactDbService.getCustomerIdAndContactNameAndAccountId(customerContactVO.getCustomerId(),customerContactVO.getContactName(),customerContactVO.getContactInformation(),customerContactVO.getContactNature(),userAccount.getAccountId());
        Contact contact = contactList.get(0);
        contact.setContactPosition(customerContactVO.getContactPosition());
        contact.setOnTheJobSituation(customerContactVO.getOnTheJobSituation());
        contact.setWx(customerContactVO.getWx());
        contact.setMailBox(customerContactVO.getMailBox());
        if(!StringUtils.isBlank(customerContactVO.getHomeAddress())) {
            contact.setHomeAddress(customerContactVO.getHomeAddress());
        }
        if(!StringUtils.isBlank(customerContactVO.getCompanyAddress())) {
            contact.setCompanyAddress(customerContactVO.getCompanyAddress());
        }
        contact.setUpdatePeopleId(userAccount.getAccountId());
        contact.setUpdateTm(new Date());
        rs = contactDbService.updateContact(contact);

        if("0".equals(customerContactVO.getContactNature())) {  //只有企业联系人的时候才做修改

            List<CustomerContactPerson> custContactList = customerDbService.getCustomerIdAndContactName(customerContactVO.getCustomerId(), customerContactVO.getContactName(), customerContactVO.getContactInformation());
            if (custContactList != null && custContactList.size() > 0) {
                CustomerContactPerson customerContactPerson = custContactList.get(0);
                //把修改的数据存放到修改信息表里
                //比较职务  contactPosition
                /*if (!(customerContactVO.getContactPosition()).equals(customerContactPerson.getContactPosition())) {
                    insertModificationRecord(2, customerContactPerson.getContactPosition(), customerContactVO.getContactPosition(), customerContactVO.getCustomerId(), userAccount.getAccountId());
                }

                //在职情况	onTheJobSituation
                if (!(customerContactVO.getOnTheJobSituation()).equals(customerContactPerson.getOnTheJobSituation())) {
                    insertModificationRecord(3, customerContactPerson.getOnTheJobSituation().toString(), customerContactVO.getOnTheJobSituation().toString(), customerContactVO.getCustomerId(), userAccount.getAccountId());
                }
                //邮箱		mailBox
                if (!(customerContactVO.getMailBox()).equals(customerContactPerson.getMailBox())) {
                    insertModificationRecord(5, customerContactPerson.getMailBox(), customerContactVO.getMailBox(), customerContactVO.getCustomerId(), userAccount.getAccountId());
                }
                //微信		wx
                if (!(customerContactVO.getWx()).equals(customerContactPerson.getWx())) {
                    insertModificationRecord(6, customerContactPerson.getWx(), customerContactVO.getWx(), customerContactVO.getCustomerId(), userAccount.getAccountId());
                }*/
            /*//家庭地址		homeAddress
            if (!(customerContactVO.getHomeAddress()).equals(customerContactPerson.getH)) {
                insertModificationRecord(8,customerContactPerson.getWx(),customerContactVO.getWx(),customerContactVO.getCustomerId(),userAccount.getAccountId());
            }
            //公司地址		companyAddress
            if (!(customerContactVO.getWx()).equals(customerContactPerson.getWx())) {
                insertModificationRecord(9,customerContactPerson.getWx(),customerContactVO.getWx(),customerContactVO.getCustomerId(),userAccount.getAccountId());
            }*/


                //customerContactPerson.setContactName(customerContactVO.getContactName());
                customerContactPerson.setContactPosition(customerContactVO.getContactPosition());
                //customerContactPerson.setContactInformation(customerContactVO.getContactInformation());
                customerContactPerson.setOnTheJobSituation(customerContactVO.getOnTheJobSituation());
                customerContactPerson.setWx(customerContactVO.getWx());
                customerContactPerson.setMailBox(customerContactVO.getMailBox());
                //customerContactPerson.setContactState(customerContactVO.getContactState());
                customerContactPerson.setUpdatePeopleId(userAccount.getAccountId());
                customerContactPerson.setUpdateTm(new Date());
                boolean result = customerPoolDbService.updateCustomerContactPerson(customerContactPerson);
            }
        }
            if (rs == true) {
                return rs;
            } else {
                return rs;
            }


    }

    /**
     * 往修改记录表里添加数据
     * @param code 字段名代表
     * @param beforeName 修改前
     * @param afterName 修改后
     * @param customerId 客户id
     * @param accountId 用户id
     */
    public void insertModificationRecord(int code,String beforeName,String afterName,String customerId,String accountId) {
        ModificationRecord modificationRecord = new ModificationRecord();
        String modificationRecordId = CommonUtils.getGUID();
        modificationRecord.setModificationRecordId(modificationRecordId);
        modificationRecord.setModificationName(ModificationEnum.getNameByCode(code));
        modificationRecord.setBeforeModification(beforeName);
        modificationRecord.setAfterModification(afterName);
        modificationRecord.setVerifyStatus(3);
        modificationRecord.setCreatePeopleId(accountId);
        modificationRecord.setCreateTm(new Date());
        modificationRecord.setUpdatePeopleId(accountId);
        modificationRecord.setUpdateTm(new Date());
        modificationRecord.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        modificationRecord.setCustomerId(customerId);
        customerPoolDbService.addModificationRecord(modificationRecord);
    }

    /**
     * 根据客户id查询公司修改记录
     * @param pageIndex 页码
     * @param pageSize 分页大小
     * @param sortName 排序列名字
     * @param sortOrder 排序规则(asc/desc)
     * @param customerId 客户id
     * @return
     */
    @Override
    public DhPageInfo<ModificationRecordVO> modificationRecordList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String customerId) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        String order = "cmr.create_tm desc";

        List<ModificationRecordVO> list = customerPoolDbService.modificationRecordList(order, customerId);
        PageInfo<ModificationRecordVO> pageInfo = new PageInfo<ModificationRecordVO>(list);
        return new DhPageInfo<ModificationRecordVO>(pageInfo, list);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public int editCustomerPoolById(CustomerPoolAddQO customerPoolAddQO) {
        String customerPoolId = customerPoolAddQO.getCustomerPoolId();
        if (!StringUtils.isBlank(customerPoolId)) {
            String customerPoolName = customerPoolAddQO.getCustomerPoolName();
            //1、根据客户池名称判断客户池是否存在
            Boolean customerPoolRepeated = customerPoolDbService.isCustomerPoolRepeated(customerPoolName, customerPoolId);
            if (!customerPoolRepeated) {
                //2、修改客户池
                editCustomerPool(customerPoolAddQO);
                //3、删除客户池公司表
                customerPoolCompanyService.deleteCustomerPoolCompanyByCluePoolId(customerPoolId);
                //4、删除客户池规则表
                customerPoolRuleService.deleteCustomerPoolRuleByCluePoolId(customerPoolId);
                if (customerPoolAddQO.getNature() == CluePoolNatureEnum.BRANCH_PUBLIC_POOL.getCluePoolNatureCode()) {
                    //5、添加客户池公司表
                    customerPoolCompanyService.addCustomerPoolCompany(customerPoolAddQO.getCompanyIdList(), customerPoolId);
                }
                //6、添加客户池规则表
                customerPoolRuleService.addCustomerPoolRule(customerPoolAddQO, customerPoolId);
                return 0;
            } else {
                return 1;
            }
        }
        return 2;
    }

    /**
     * 客户详情--联系人 开启/废止联系人
     * @param fa 废止联系人实体
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class})
    public Boolean updateAbolishStateById(FzCustomerContactVO fa) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        //废止客户下联系人
        List<CustomerContactPerson> custContactList = customerDbService.getCustomerIdAndContactName(fa.getCustomerId(), fa.getContactName(),fa.getContactInformation());
        if(custContactList.size()!= 0){
            CustomerContactPerson customerContactPerson = custContactList.get(0);
            customerContactPerson.setAbolishState(Integer.parseInt(fa.getAbolishState()));
            customerContactPerson.setUpdatePeopleId(userAccount.getAccountId());
            customerContactPerson.setUpdateTm(new Date());
            customerPoolDbService.updateAbolishStateById(customerContactPerson);
        }
        //废止联系人
        List<Contact> contactList = contactDbService.getCustomerIdAndContactNameAndAccountId(fa.getCustomerId(),fa.getContactName(),fa.getContactInformation(),fa.getContactNature(),userAccount.getAccountId());
        if(contactList.size() != 0) {
            Contact contact = contactList.get(0);
            contact.setAbolishState(Integer.parseInt(fa.getAbolishState()));
            contact.setUpdatePeopleId(userAccount.getAccountId());
            contact.setUpdateTm(new Date());
            contactDbService.updateAbolishStateById(contact);

            //废止联系方式    通过联系人id查询下面的联系方式
            List<ContactInformation> contactInformationList = contactInformationDbService.contactInformationList("create_tm desc",contact.getContactId());
            for(ContactInformation contactInformation : contactInformationList){
                contactInformation.setAbolishState(Integer.parseInt(fa.getAbolishState()));
                contactInformation.setUpdatePeopleId(userAccount.getAccountId());
                contactInformation.setUpdateTm(new Date());
                contactInformationDbService.updateAbolishStateById(contactInformation);
            }

        }



        return true;
    }

    /**
     * 客户-修改客户
     * @param customer 客户实体    存入修改记录中
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class})
    public Boolean updateCustomer(Customer customer)  {
        boolean result = false;
        Customer customers = customerPoolDbService.getCustomer(customer.getCustomerId());
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //把修改的数据存放到修改信息表里
        try {

            Class c = Class.forName("com.crm.model.entity.customerManager.Customer"); //要包名+类名
            Customer o = (Customer) c.newInstance();
            o = customer;  //修改后
            Field[] fields = c.getDeclaredFields();//拿到数据成员

            Class cy = Class.forName("com.crm.model.entity.customerManager.Customer"); //要包名+类名
            Customer oy = (Customer) cy.newInstance();
            oy = customers;  //修改前
            Field[] fieldy = cy.getDeclaredFields();//拿到数据成员
            for (Field f : fields) {
                String nameAfter = "";
                nameAfter = matchValue(f,o);
                for (Field fy : fieldy) {
                    String nameBefore = "";
                    if (f.getName().equals(fy.getName())) {
                        nameBefore = matchValue(fy,oy);
                        if(!StringUtils.isBlank(nameAfter) && !StringUtils.isBlank(nameBefore)){
                            if (!nameAfter.equals(nameBefore)) {
                                ModificationRecord modificationRecord = new ModificationRecord();
                                String modificationRecordId = CommonUtils.getGUID();
                                modificationRecord.setModificationRecordId(modificationRecordId);
                                modificationRecord.setModificationName(CustomerEnum.getNameByCode(f.getName()));
                                if(nameBefore == null) {
                                    modificationRecord.setBeforeModification("");
                                }else{
                                    modificationRecord.setBeforeModification(nameBefore); //修改前
                                }
                                if(nameAfter == null){
                                    modificationRecord.setAfterModification("");
                                }else{
                                    modificationRecord.setAfterModification(nameAfter); //修改后
                                }
                                modificationRecord.setVerifyStatus(3);
                                modificationRecord.setCreatePeopleId(userAccount.getAccountId());
                                modificationRecord.setCreateTm(new Date());
                                modificationRecord.setUpdatePeopleId(userAccount.getAccountId());
                                modificationRecord.setUpdateTm(new Date());
                                modificationRecord.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
                                modificationRecord.setCustomerId(customer.getCustomerId());
                                boolean bs = customerPoolDbService.addModificationRecord(modificationRecord);
                                continue;
                            }
                        }

                        /*else{

                        }*/


                    }
                }
            }
            customer.setUpdatePeopleId(userAccount.getAccountId());
            customer.setUpdateTm(new Date());
            customer.setAccountId(userAccount.getAccountId());
            result = customerPoolDbService.updateCustomer(customer);
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 匹配相同的参数,取到值
     * @param fy 成员变量
     * @param oy 客户的值
     * @return
     */
    public static String matchValue(Field fy,Customer oy){
        String name="";
        //参与修改的字段
        if (fy.getName().equals("customerName") ||
                //fy.getName().equals("tag") ||
                fy.getName().equals("customerType") ||
//                fy.getName().equals("customerNumber") ||
//                fy.getName().equals("originalCustomerId") ||
                fy.getName().equals("unifiedSocialCreditCode") ||
                fy.getName().equals("companyType") ||
                fy.getName().equals("industry") ||
                fy.getName().equals("companySize") ||
                fy.getName().equals("registeredCapital") ||
                fy.getName().equals("contactPerson") ||
                fy.getName().equals("contactPersonPhone")||
                fy.getName().equals("legalRepresentative")||
                fy.getName().equals("enterpriseExternalLandline")||
                fy.getName().equals("companyWebsite")||
//                fy.getName().equals("fax")||
                fy.getName().equals("email")||
                fy.getName().equals("remark") ||
                fy.getName().equals("detailedAddress")
                //fy.getName().equals("uploadId")
        ) {
            name = (String) getFieldValueByName(fy.getName(), oy);
        } else if (fy.getName().equals("financialNumber")) {
            Integer namet = (Integer) getFieldValueByName(fy.getName(), oy);
            if("0".equals(String.valueOf(namet)) || "null".equals(String.valueOf(namet)) || namet <= 0){
                name = null;
            }else{
                name = Integer.toString(namet);
            }

        } else if (fy.getName().equals("registrationTime")) {
            Date namet = (Date) getFieldValueByName(fy.getName(), oy);
            if(namet == null) {
                name = null;
            }else{
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                name = formatter.format(namet);
            }
        }
        return name;
    }


    /**
     * 根据客户id查询客户详情
     * @param customerId
     * @return
     */
    @Override
    public CustomerVO selectByCustomerId(String customerId) {


        CustomerVO customerVO = customerDbService.selectByCustomerId(customerId);
//        short delState = (short) StatusCodeEnum.NORMAL_CODE.getState();
//        Integer level = finishOrderDBservice.productMembershipLevel(delState, customerId, "1");
//        customerVO.setMembershipLevel(level);
        return customerVO;
    }

    /**
     * 客户详情下拉框的文本
     * @param typeCode  大类
     * @param dictCode  小类
     * @return
     */
    @Override
    public Dictionary selectDictionaryByOne(String typeCode, String dictCode) {
        return dictionaryDbService.selectDictionaryByOne(typeCode,dictCode);
    }


    /**
     * 根据属性名获取属性值
     * @param fieldName  名称
     * @param o 实体类
     * @return
     */
    public static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter);
            Object value = method.invoke(o);
            return value;
        } catch (Exception e) {
            //log.error(e.getMessage(),e);
            return null;
        }
    }


    private void editCustomerPool(CustomerPoolAddQO customerPoolAddQO){
        CustomerPool customerPool = customerPoolDbService.selectCustomerPoolById(customerPoolAddQO.getCustomerPoolId());
        //获取当前用户
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //customerPool.setCustomerPoolId(customerPoolAddQO.getCustomerPoolId());
        customerPool.setCustomerPoolName(customerPoolAddQO.getCustomerPoolName());
        customerPool.setProvinceId(customerPoolAddQO.getProvinceId());
        customerPool.setProvinceName(customerPoolAddQO.getProvinceName());
        customerPool.setCityId(customerPoolAddQO.getCityId());
        customerPool.setCityName(customerPoolAddQO.getCityName());
        customerPool.setIndustry(customerPoolAddQO.getIndustry());
        customerPool.setSource(customerPoolAddQO.getSource());
        customerPool.setPoolType(customerPoolAddQO.getPoolType());
        customerPool.setCapacity(customerPoolAddQO.getCapacity());
        customerPool.setNature(customerPoolAddQO.getNature());
        customerPool.setTag(customerPoolAddQO.getTag());
        customerPool.setPoolDetail(customerPoolAddQO.getPoolDetail());
        customerPool.setUpdatePeopleId(userAccount.getAccountId());
        customerPool.setUpdateTm(new Date());
        customerPool.setAffiliatedCompanyId(customerPoolAddQO.getAffiliatedCompanyId());
        customerPoolDbService.updatePoolStateById(customerPool);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public int deleteCustomerPoolById(String customerPoolId) {
        short deleteStatus = Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState()));
        //1、删除客户池
        CustomerPool customerPool = new CustomerPool();
        if(!StringUtils.isBlank(customerPoolId)){
            customerPool.setCustomerPoolId(customerPoolId);
            customerPool.setDeleteStatus(deleteStatus);
        }
        List<String> customerIdList = customerService.selectCustomerIdList(customerPoolId);
        if(customerIdList != null && !customerIdList.isEmpty()){
            //2、删除客户
            customerService.batchDeleteCustomerByCustomerIds(customerIdList, deleteStatus);
        }
        customerPoolDbService.updatePoolStateById(customerPool);
        //3、删除客户池公司
        customerPoolCompanyService.deleteCustomerPoolCompanyByCluePoolId(customerPoolId);
        //4、删除客户池规则
        customerPoolRuleService.deleteCustomerPoolRuleByCluePoolId(customerPoolId);
        return 0;
    }

    /**
     * 根据客户ID查询公司
     * @param customerPoolId  ---客户池ID
     * @return
     */
    @Override
    public List<UserCompanyVO> selectDistributeCompany(String customerPoolId) {
        return customerPoolDbService.selectDistributeCompany(customerPoolId);
    }

    /**
     * 根据用户名查询用户信息及所在公司信息(全国公有池、分公司公有池-分配-按人员姓名模糊查找)
     * @param userName ---用户名
     * @return
     */
    @Override
    public List<UserCompanyVO> selectUserAndCompany(String userName) {
        return customerPoolDbService.selectUserAndCompany(userName);
    }

    /**
     * 查询分公司公有池的用户
     * @param companyIds ---公司ID集合
     * @param userName ---用户名
     * @return
     */
    @Override
    public  List<UserCompanyVO> selectUserByPoolPermission(List<String> companyIds,String userName) {
        return customerPoolDbService.selectUserByPoolPermission(companyIds,userName);
    }

    @Override
    public List<CustomerPool> selectEnableCustomerPoolName() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<CustomerPool> customerPoolList = null;
        if (CommonUtils.isAdmin(userAccount.getUserId())) {//超级管理员
            customerPoolList = customerPoolDbService.selectAllEnableCustomerPoolName();
        } else {//普通管理员
            String companyId = userAccount.getCompanyId();//获取登录人所在的公司
            customerPoolList = customerPoolDbService.selectPartEnableCustomerPoolName(companyId);
        }
        return customerPoolList;
    }

    /**
     * 客户-修改客户图片和标签
     * @param customer 客户实体
     * 备注(管理端-内训线索池-内训详情修改客户图片也引用了)
     * @return
     */
    @Override
    public Boolean updateCustomerImgAndTag(Customer customer) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Customer cust = customerDbService.selectCustomerById(customer.getCustomerId());

        boolean rs = customerPoolDbService.updateCustomer(customer);

        if(!StringUtils.isBlank(customer.getUploadId())) {
            insertModificationRecord(10,cust.getUploadId(),customer.getUploadId(),customer.getCustomerId(),userAccount.getAccountId());
        }

        if (!StringUtils.isBlank(customer.getTag())) {
            insertModificationRecord(11,cust.getTag(),customer.getTag(),customer.getCustomerId(),userAccount.getAccountId());
        }

        if (!StringUtils.isBlank(customer.getSystemTag())) {
            insertModificationRecord(14,cust.getSystemTag(),customer.getSystemTag(),customer.getCustomerId(),userAccount.getAccountId());
        }


        return rs;
    }
}
